package com.qfedu.dtboot.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.qfedu.dtboot.util.R;
import com.qfedu.dtboot.util.ShiroUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.Map;

/**
 * @ClassName SysLoginController
 * @Author ykx
 * @Date 2022/9/28 13:21
 * @Version 1.0
 */
@Controller
public class SysLoginController {

    @Autowired
    private Producer producer;

    @RequestMapping("/captcha.jpg")
    public void kaptcha(HttpServletResponse response) throws Exception{

        response.setHeader("Cache-Control","no-store,no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();

        //生成图片验证码
        BufferedImage image = producer.createImage(text);

        //保存在session中
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY,text);

        //响应给客户端
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"jpg",outputStream);
        outputStream.flush();
    }

    @ResponseBody
    @PostMapping("/sys/login")
    public R login(@RequestBody Map<String,String> map){
        String username = map.get("username");
        String password = map.get("password");
        String captcha = map.get("captcha");
        String rememberMe = map.get("rememberMe");


        String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
        if (!kaptcha.equalsIgnoreCase(captcha)){
            return R.error("验证码错误");
        }

        boolean remember = false;
        if (rememberMe!=null){
            remember = true;
        }

        Subject subject = ShiroUtils.getSubject();

        try {
            password = new Md5Hash(password,username,1024).toHex();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            token.setRememberMe(remember);
            subject.login(token);
        }catch (UnknownAccountException | IncorrectCredentialsException | LockedAccountException e){
            return R.error(e.getMessage());
        } catch (AuthenticationException e){
            return R.error("账户验证失败");
        }
            return R.ok();
    }

    @GetMapping("logout")
    public String logout(){
        ShiroUtils.logout();
        return "redirect:login.html";
    }
}

